package com.example.nasa.feed;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.nasa.parse.IotdHandler;

public class NasaIOTDActivity extends Activity {
	private ProgressDialog dialog;
	private volatile Handler handler;
	private static IotdHandler iotdHandler;
	private AlertDialog alertDialog;
	private Bitmap imageOfTheDay;
	private static Thread processingThread;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nasa_activity_main);
        if(isOnline()){
        	handler = new Handler();
        	refreshFromFeed();
        }else{
			internetConnectionError();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    protected void onDestroy() {
    	if(dialog != null && dialog.isShowing()){
    		dialog.dismiss();
    	}
    	if(alertDialog != null && alertDialog.isShowing()){
    		alertDialog.dismiss();
    	}
    	if(processingThread != null && processingThread.isAlive()){
    		processingThread.interrupt();
    	}
    	handler = new Handler();
    	super.onDestroy();
    }
    /**
     * Mehotd that update the information on the screen.
     * @param view
     */
    public void onRefresh(View view){
    	if(isOnline()){
    		iotdHandler = null;
    		refreshFromFeed();
    	}else{
    		handler.post(new Runnable(){
    			public void run(){
    				internetConnectionError();
    			}
    		});
    	}
    }
    
    /**
     * Repaint method.
     * @param title
     * @param date
     * @param imageUrl
     * @param description
     */
    private void resetDisplay(String title, String date, Bitmap imageUrl, String description) {
    	TextView textTitle = (TextView) findViewById(R.id.imageTitle);
    	textTitle.setText(title);
    	TextView textDate = (TextView) findViewById(R.id.imageDate);
    	textDate.setText(date);
    	ImageView image = (ImageView)findViewById(R.id.imageDisplay);
    	image.setImageBitmap(imageUrl);
    	TextView desc = (TextView) findViewById(R.id.imageDescription);
    	desc.setText(description);
    }
    
    /**
     * Method that initiate the connection, download and parse the xml.
     */
    public void refreshFromFeed(){
		processingThread = new Thread(){
			public void run(){
				if(iotdHandler == null){
					iotdHandler = new IotdHandler();
				}
				try {
					if(iotdHandler.getTitle() == null){
						iotdHandler.processFeed();
					}
					imageOfTheDay = iotdHandler.getImage();
					handler.post(new Runnable(){
						public void run(){
							NasaIOTDActivity.this.onLongClickSaveDialogShow();
							resetDisplay(iotdHandler.getTitle(), iotdHandler.getDate(),	iotdHandler.getImage(), iotdHandler.getDescription());
							iotdHandler.reset();
							if(dialog != null && dialog.isShowing()){
								dialog.dismiss();
							}
						}
					});
				} catch (Exception e){
					e.printStackTrace();
					if(dialog != null && dialog.isShowing()){
						dialog.dismiss();
					}
					handler.post(new Runnable(){
						public void run(){
							internetConnectionError();
						}
					});
				}
			}
		};
		dialog = ProgressDialog.show(
				this,
				"Loading",
				"Please wait...",
				true,
				true,
				new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						NasaIOTDActivity.this.finish();
					}
				});
		processingThread.start();
    }
    
    /**
     * Method called when user select to save the image.
     * @param view
     */
    private void onSaveFile(View view){
		processingThread = new Thread(){
			public void run(){
				try{
					ByteArrayOutputStream bytes = new ByteArrayOutputStream();
					imageOfTheDay.compress(Bitmap.CompressFormat.PNG, 100, bytes);
					SimpleDateFormat formatador = new SimpleDateFormat("dd_MM_yyyy_-_HH_mm_ss");
					File f = new File(Environment.getExternalStorageDirectory() +
										File.separator +
										"NasaFeed");
					if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
						if(!f.exists()){
							f.mkdir();
						}
						f = new File(Environment.getExternalStorageDirectory() +
								File.separator +
								"NasaFeed" +
								File.separator +
								"Picture_of_the_Day_-_"+ formatador.format(new Date()) +".png");
						f.createNewFile();
						FileOutputStream fo = new FileOutputStream(f);
						fo.write(bytes.toByteArray());
						fo.close();
					}else{
						Toast.makeText(NasaIOTDActivity.this,"Could not acess SDCard",Toast.LENGTH_LONG).show();
					}
					handler.post(new Runnable(){
						public void run(){
							Toast.makeText(NasaIOTDActivity.this,"Picture saved =)",Toast.LENGTH_SHORT).show();
						}
					});
				}catch(Exception e){
					e.printStackTrace();
					handler.post(new Runnable(){
						public void run(){
							Toast.makeText(NasaIOTDActivity.this,"Error saving picture",Toast.LENGTH_SHORT).show();
						}
					});
				}
			}
		};
		processingThread.start();
    }
    
    /**
     * Method that verifies internet connection avaliability.
     * @return
     */
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            return true;
        }
        return false;
    }
    
    /**
     * Error dialog when no connection found.
     */
    private void internetConnectionError(){
    	alertDialog = new AlertDialog.Builder(NasaIOTDActivity.this).create();
        alertDialog.setTitle("Error");
        alertDialog.setMessage("Cannot connect to NASA server.");
        alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
        	  if(alertDialog != null && alertDialog.isShowing()){
        		  alertDialog.dismiss();
				}
        	  NasaIOTDActivity.this.finish();
        } });
        alertDialog.show();
    }
    
    /**
     * Show the dialog when user performs a long press on the image.
     */
    private void onLongClickSaveDialogShow() {
		ImageView imageView = (ImageView) findViewById(R.id.imageDisplay);
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
			@Override
			public boolean onLongClick(final View view) {
				final Vibrator vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
				vibrator.vibrate(100);
				alertDialog = new AlertDialog.Builder(NasaIOTDActivity.this).create();
	            alertDialog.setTitle("Save");
	            alertDialog.setMessage("Save this picture?");
	            alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						NasaIOTDActivity.this.alertDialog.dismiss();
						NasaIOTDActivity.this.onSaveFile(view);
					}
	             });
	            alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
	            	public void onClick(DialogInterface dialog, int which) {
	            		NasaIOTDActivity.this.alertDialog.dismiss();
	            	}
	            });
	            alertDialog.show();
				return false;
			}
		});
	}
}

